package com.tc.nacos.config.test;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import lombok.extern.slf4j.Slf4j;

import java.util.Properties;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;

/**
 * @Auther: tianchao
 * @Date: 2021/10/10 21:55
 * @Description:
 */
@Slf4j
public class ConfigServerDemo {
    public static void main(String[] args) throws NacosException, InterruptedException {
        String serverAddr = "127.0.0.1:8848";
        String dataId = "ext-shared-00.yaml";
        String group = "DEFAULT_GROUP";
        String namespace = "0cd5d1f5-fb51-4c35-b7e9-c2ef8ee1102b";
        Properties properties = new Properties();
        properties.put(PropertyKeyConst.SERVER_ADDR, serverAddr);
        properties.put(PropertyKeyConst.NAMESPACE, namespace);
        // 获取配置中心服务
        ConfigService configService = NacosFactory.createConfigService(properties);
        //从配置中心拉取配置
        String config = configService.getConfig(dataId, group, 50000);
        log.info("第一次获取配置信息 : {}",config);
        //注册监听器
        configService.addListener(dataId, group, new Listener() {
            @Override
            public Executor getExecutor() {
                return null;
            }

            @Override
            public void receiveConfigInfo(String configInfo) {
                log.info(Thread.currentThread().getName());
                log.info("感知配置变化:" + configInfo);
            }
        });
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        TimeUnit.SECONDS.sleep(3);
        configService.publishConfig(dataId, group, "e=f");
        TimeUnit.SECONDS.sleep(3);
        config = configService.getConfig(dataId, group, 50000);
        log.info("主动拉取:{}",config);
        TimeUnit.SECONDS.sleep(5000);
    }
}
